<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>获取选中的文本</title>
</head>
<body>
    <div id="test">选中这段文本然后再点击我</div>
    <script>
        const getSelectionText = () => window.getSelection().toString();
        document.querySelector('#test').addEventListener('click',() => {
            const selectText = getSelectionText();
            if(!selectText){
                return alert("请先选中文本");
            }
            alert('你选中的是: ' + selectText);
        })
    </script>
</body>
</html>